//
//  BaseApiManager.swift
//  AJiTai
//
//  Created by BO ZHOU on 2020/5/16.
//  Copyright © 2020 BO ZHOU. All rights reserved.
//

import Foundation
import Alamofire
import HandyJSON


open class BaseApiManager: NSObject {
    
    static var baseUrl: String = ""
    
    /** 是否打印log */
    static var isPrintLog = true

    /** api请求头 */
    static var headers: HTTPHeaders = [
        "Content-Type": "application/json"
    ]

    /** 是否需要debug接口响应时间 */
    static var apiNeedDebug: Bool = true

    // 网络请求 (GET POST)
    class func request(withPath: String,
                       method: HTTPMethod = .post,
                       parameters: [String: Any]?,
                       showLoading: Bool = true,
                       loadingInView: UIView? = nil,
                       showError: Bool = true,
                       errorInView: UIView? = nil,
                       callBackBlock: ((_ isSuccess: Bool, _ response: [String: Any]?)->())?) -> DataRequest? {
        
        // 防止子路径开头有多余的/
        var subPath = withPath
        if subPath.hasPrefix("/") {
            subPath = String(subPath.suffix(from: subPath.index(subPath.startIndex, offsetBy: 1)))
        }
        
        let url = baseUrl + subPath
        
        return _request(withFullPath: url, method: method, parameters: parameters, showLoading: showLoading, loadingInView: loadingInView, showError: showError, _errorInView: errorInView, callBackBlock: callBackBlock)

    }
    
    
    // 全路径请求, 忽略baseUrl
    // 网络请求 (GET POST)
    class func request(withAbsolutePath: String,
                       method: HTTPMethod = .post,
                       parameters: [String: Any]?,
                       showLoading: Bool = true,
                       loadingInView: UIView? = nil,
                       showError: Bool = true,
                       errorInView: UIView? = nil,
                       callBackBlock: ((_ isSuccess: Bool, _ response: [String: Any]?)->())?) -> DataRequest? {
        
        return _request(withFullPath: withAbsolutePath, method: method, parameters: parameters, showLoading: showLoading, loadingInView: loadingInView, showError: showError, _errorInView: errorInView, callBackBlock: callBackBlock)
    }
    
    
    
    // 如果errorInView为空, showError为true, 默认errorInView = loadingInView
    private class func _request(withFullPath: String,
                       method: HTTPMethod = .post,
                       parameters: [String: Any]?,
                       showLoading: Bool = true,
                       loadingInView: UIView? = nil,
                       showError: Bool = true,
                       _errorInView: UIView? = nil,
                       callBackBlock: ((_ isSuccess: Bool, _ response: [String: Any]?)->())?) -> DataRequest? {
        
        // 处理encoding
        var encoding: ParameterEncoding = JSONEncoding.default
        if method == .get {
            encoding = URLEncoding.default
        }

        var errorInView = _errorInView
        if showError && errorInView == nil {
            errorInView = loadingInView
        }
        
        let loadingview = showLoadingView(showLoading: showLoading, loadingInView: loadingInView)
        
        var apiStartDate: Date? = nil
        if apiNeedDebug {
            apiStartDate = Date()
        }
        
        return AF.request(withFullPath, method: method, parameters: parameters, encoding: encoding, headers: headers).responseJSON { (dataResponse) in

            loadingview?.superview?.hideNetWorkLoding()

            let task = {
                _ = _request(withFullPath: withFullPath, method: method, parameters: parameters, showLoading: showLoading, loadingInView: loadingInView, showError: showError, _errorInView: _errorInView, callBackBlock: callBackBlock)
            }

            guard let data = dataResponse.value else {
                
                // 如果数据不存在, 返回异常
                var dic: [String: Any] = [String: Any]()
                let error = dataResponse.error
                dic.updateValue(error.debugDescription, forKey: "msg")
                callBackBlock?(false, dic)
                
                showErrorView(showError: showError, errorInView: errorInView, task: task)
                return
            }
            
            // 数据转字典
            guard let dict = data as? [String : Any] else {
                
                // 数据解析失败, 返回异常
//                self.showError(message: "数据解析失败")
                callBackBlock?(false, nil)
                
                showErrorView(showError: showError, errorInView: errorInView, task: task)
                return
            }
                  
            self.apiEnd(withFullPath: withFullPath, method: method, headers: headers, parameters: parameters, dict: dict, apiStartDate: apiStartDate)
            
            
            if let code: Int = dict["code"] as? Int {
                dealApiCode(code: code, showError: showError, errorInView: errorInView, dict: dict, task: task, callBackBlock: callBackBlock)
            } else if let code = dict["status"] as? Int {
                dealApiCode(code: code, showError: showError, errorInView: errorInView, dict: dict, task: task, callBackBlock: callBackBlock)
            }
        }
    }
    
    
    private class func dealApiCode(code: Int, showError: Bool, errorInView: UIView?, dict: [String: Any], task: (()->Void)?, callBackBlock: ((_ isSuccess: Bool, _ response: [String: Any]?)->())?) {
        if code == 200 {
            
            hideErrorView(showError: showError, errorInView: errorInView)
            
            // 接口正常系
            callBackBlock?(true, dict)
        } else {
            
            if code == 401 || code == -1 {
                
                // 回到登录页面
                 self.logout()
            } else {
                                        
                // 接口异常系
                callBackBlock?(false, dict)
                
                showErrorView(showError: showError, errorInView: errorInView, task: task)
            }
        }
    }
    
    
    open class func uploadImage(url: String,
                                  images: [UIImage], name: String = "file",
                                  parameters: [String: Any]? = nil,
                                  showLoading: Bool = true,
                                  loadingInView: UIView? = nil,
                                  resultBlock: @escaping (_ isSuccess: Bool, _ imageId: Int?, _ errorMsg: String?)->Void) {
        
        let headers: HTTPHeaders
        headers = ["Content-type": "multipart/form-data",
                   "Content-Disposition" : "form-data"]

        
        let loadingview = showLoadingView(showLoading: showLoading, loadingInView: loadingInView)

        AF.upload(multipartFormData: { (multipartFormData) in
            if let param = parameters {
                for (key, value) in param {
                    multipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key)
                }
            }

            for img in images {
                guard let imgData = img.compressImage_data(toByte: 9 * 1024) else { return }
                multipartFormData.append(imgData, withName: name, fileName: "123" + ".jpeg", mimeType: "image/jpeg")
            }


        },to: url, usingThreshold: UInt64.init(),
          method: .post,
          headers: headers).response{ response in

            loadingview?.superview?.hideNetWorkLoding()

            if((response.error != nil)) {
                
                resultBlock(false, nil, "未知错误")

//                do{
//                    if let jsonData = response.data{
//                        let parsedData = try JSONSerialization.jsonObject(with: jsonData) as! Dictionary<String, AnyObject>
//                        print(parsedData)
//                    }
//                }catch{
//                    print("error message")
//                }
            }else{
                do{
                    if let jsonData = response.data{
                        let parsedData = try JSONSerialization.jsonObject(with: jsonData) as! Dictionary<String, AnyObject>
                        
                        if let code = parsedData["code"] as? Int {
                            if code == 200 {
                                if let imageIndex = parsedData["data"] as? Int {
                                    
                                    resultBlock(true, imageIndex, nil)
                                    return
                                }
                            }
                            
                            if let msg = parsedData["msg"] as? String {
                                resultBlock(false, nil, msg)
                            } else {
                                resultBlock(false, nil, "未知错误")
                            }
                        } else {
                            resultBlock(false, nil, "未知错误")
                        }
                    }
                }catch{
                    print("error message")
                }
            }
        }
    }
    
    
    open class func uploadAppImage(url:String, images: [UIImage], name: String = "file", parameters: [String: Any]? = nil, resultBlock: @escaping (_ isSuccess: Bool, _ imageId: Int?, _ errorMsg: String?)->Void) {
        
        uploadImage(url: url, images: images, name: name, parameters: parameters, resultBlock: resultBlock)
    }

    
}



// 建议在不同的项目, 将登录和退出登录放在BaseApiManager扩展里
extension BaseApiManager {
    
    
    // 退出登录 (换项目需要删除)
//    class func logout() {
//        UIApplication.shared.keyWindow!.rootViewController = UIStoryboard.init(name: "Auth", bundle: nil).instantiateInitialViewController()
//        LoginUserModel.removeLoginUserModel()
//    }

    
    class func logout() {
        // 删除本地loginmodel
//        LoginApiModel.deleteLocalModel()
//        
//        
//        // 删除别名
//        JPUSHService.deleteAlias({ (in , str , in2) in
//            print("....")
//        }, seq: 2)
//        
//        changeRootViewControllerAnimation(controller: LoginViewController.getVCInstance())
    }
}

